from flask import Blueprint, request, jsonify, g
from app.models import (
    User, APIKey, AIServer, AIModel, SystemConfig,
    DoesNotExist, datetime
)
from app.utils import admin_required

admin_bp = Blueprint('admin', __name__)

@admin_bp.route('/users', methods=['GET'])
@admin_required
async def get_users():
    """获取所有用户列表"""
    users = User.select().order_by(User.created_at.desc())
    return jsonify([{
        'id': u.id,
        'username': u.username,
        'email': u.email,
        'is_admin': u.is_admin,
        'created_at': u.created_at.isoformat()
    } for u in users])

@admin_bp.route('/users/<int:user_id>/toggle-admin', methods=['POST'])
@admin_required
async def toggle_admin(user_id):
    """切换用户管理员权限"""
    try:
        user = User.get(User.id == user_id)
        # 不能取消自己的管理员权限
        if user.id == g.user.id and not user.is_admin:
            return jsonify({'error': '不能取消自己的管理员权限'}), 400
            
        user.is_admin = not user.is_admin
        user.save()
        return jsonify({
            'status': 'success',
            'user_id': user.id,
            'is_admin': user.is_admin
        })
    except DoesNotExist:
        return jsonify({'error': '用户不存在'}), 404

@admin_bp.route('/api-keys/pending', methods=['GET'])
@admin_required
async def get_pending_api_keys():
    """获取待激活的API Key"""
    pending_keys = (APIKey
                   .select(APIKey, User.username)
                   .join(User)
                   .where(
                       (APIKey.is_active == False) & 
                       (APIKey.is_revoked == False)
                   )
                   .order_by(APIKey.created_at.asc()))
    
    return jsonify([{
        'id': k.id,
        'user_id': k.user.id,
        'username': k.user.username,
        'description': k.description,
        'created_at': k.created_at.isoformat()
    } for k in pending_keys])

@admin_bp.route('/api-keys/activate', methods=['POST'])
@admin_required
async def activate_api_key():
    """激活API Key"""
    key_id = request.form.get('key_id','')

    try:
        api_key = APIKey.get(
            (APIKey.id == key_id) &
            (APIKey.is_active == False) &
            (APIKey.is_revoked == False)
        )
        
        api_key.is_active = True
        api_key.activated_at = datetime.datetime.now()
        api_key.activated_by = g.user
        api_key.save()
        
        return jsonify({'status': 'success', 'message': 'API Key已激活'})
    except DoesNotExist:
        return jsonify({'error': 'API Key不存在或已处理'}), 404


@admin_bp.route('/api-keys/activate', methods=['POST'])
@admin_required
async def revoke_api_key():
    """删除/拒绝API Key"""
    key_id = request.form.get('key_id','')

    try:
        api_key = APIKey.get(
            (APIKey.id == key_id) 
        )
        
        api_key.is_revoked = True
        api_key.save()
        
        return jsonify({'status': 'success', 'message': 'API Key已激活'})
    except DoesNotExist:
        return jsonify({'error': 'API Key不存在或已处理'}), 404

@admin_bp.route('/ai-servers', methods=['GET'])
@admin_required
async def get_ai_servers():
    """获取所有AI服务器"""
    servers = AIServer.select().order_by(AIServer.name)
    return jsonify([{
        'id': s.id,
        'name': s.name,
        'url': s.url,
        'description': s.description,
        'is_active': s.is_active,
        'created_at': s.created_at.isoformat()
    } for s in servers])

@admin_bp.route('/ai-servers', methods=['POST'])
@admin_required
async def create_ai_server():
    """添加新的AI服务器"""
    data = request.get_json() or {}
    if not all(k in data for k in ['name', 'url']):
        return jsonify({'error': '服务器名称和URL为必填项'}), 400
    
    try:
        server = AIServer.create(
            name=data['name'],
            url=data['url'],
            description=data.get('description'),
            is_active=data.get('is_active', True)
        )
        
        # 如果是第一个服务器，设为默认
        if AIServer.select().count() == 1:
            SystemConfig.set_default('default_ai_server', str(server.id), g.user)
            
        return jsonify({
            'id': server.id,
            'name': server.name,
            'url': server.url
        }), 201
    except Exception as e:
        return jsonify({'error': f'添加服务器失败：{str(e)}'}), 500

@admin_bp.route('/ai-models', methods=['GET'])
@admin_required
async def get_ai_models():
    """获取所有AI模型"""
    models = (AIModel
             .select(AIModel, AIServer.name.alias('server_name'))
             .join(AIServer)
             .order_by(AIModel.name))
    
    return jsonify([{
        'id': m.id,
        'name': m.name,
        'server_id': m.server.id,
        'server_name': m.server.name,
        'description': m.description,
        'is_active': m.is_active,
        'created_at': m.created_at.isoformat()
    } for m in models])

@admin_bp.route('/ai-models', methods=['POST'])
@admin_required
async def create_ai_model():
    """添加新的AI模型"""
    data = request.get_json() or {}
    if not all(k in data for k in ['server_id', 'name']):
        return jsonify({'error': '服务器ID和模型名称为必填项'}), 400
    
    try:
        # 验证服务器存在
        AIServer.get(AIServer.id == data['server_id'])
        
        model = AIModel.create(
            server_id=data['server_id'],
            name=data['name'],
            description=data.get('description'),
            is_active=data.get('is_active', True)
        )
        
        # 如果是第一个模型，设为默认
        if AIModel.select().count() == 1:
            SystemConfig.set_default('default_ai_model', str(model.id), g.user)
            
        return jsonify({
            'id': model.id,
            'name': model.name,
            'server_id': model.server_id
        }), 201
    except DoesNotExist:
        return jsonify({'error': '服务器不存在'}), 404
    except Exception as e:
        return jsonify({'error': f'添加模型失败：{str(e)}'}), 500

@admin_bp.route('/system-config/defaults', methods=['GET'])
@admin_required
async def get_default_configs():
    """获取系统默认配置"""
    server_id = SystemConfig.get_default('default_ai_server')
    model_id = SystemConfig.get_default('default_ai_model')
    
    server = None
    if server_id:
        try:
            server = AIServer.get(AIServer.id == int(server_id))
        except DoesNotExist:
            pass
    
    model = None
    if model_id:
        try:
            model = AIModel.get(AIModel.id == int(model_id))
        except DoesNotExist:
            pass
    
    return jsonify({
        'default_ai_server': server.__data__ if server else None,
        'default_ai_model': model.__data__ if model else None
    })

@admin_bp.route('/system-config/defaults', methods=['POST'])
@admin_required
async def set_default_configs():
    """设置系统默认配置"""
    data = request.get_json() or {}
    
    if 'default_ai_server' in data:
        SystemConfig.set_default('default_ai_server', data['default_ai_server'], g.user)
    
    if 'default_ai_model' in data:
        SystemConfig.set_default('default_ai_model', data['default_ai_model'], g.user)
    
    return jsonify({'status': 'success', 'message': '默认配置已更新'})
